package com.lijin.batchsys.framework.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowCallbackHandler;

import com.lijin.batchsys.framework.common.BatchUtil;
import com.lijin.batchsys.framework.dao.model.StepInfo;

/**
 * Description: 步骤DAO实现类
 *
 * (C) Copyright of China UnionPay Co., Ltd. 2010.
 */
public class StepInfoDAO extends BaseDAO {
	
    /**
	 * 获取所有的步骤信息
	 * @return
	 */
	public List<StepInfo> getAllStep() {
		final List<StepInfo> stepList = new LinkedList<StepInfo>();
		
		this.getJdbcTemplate().query(BatchSysSQL.getInstance().fetchSQL(BatchSysSQL.SQL_SELECT_ALL_STEP), 
				new RowCallbackHandler() {
					@Override
					public void processRow(ResultSet rs) throws SQLException {
						StepInfo stepInfo = new StepInfo();
						stepInfo.setId(rs.getInt("ID"));
						stepInfo.setBatchNo(rs.getInt("BATCH_NO"));
						stepInfo.setJobNo(rs.getInt("JOB_NO"));
						stepInfo.setStepNo(rs.getInt("STEP_NO"));
						stepInfo.setStepDesc(rs.getString("STEP_DESC"));
						stepInfo.setStepBeanName(rs.getString("STEP_BEAN_NAME"));
						stepInfo.setStepRunPeriod(rs.getString("STEP_RUN_PERIOD"));
						stepInfo.setStepCtrlFlgs(rs.getString("STEP_CTRL_FLGS"));
						stepInfo.setRecSt(rs.getString("REC_ST"));
						
						stepList.add(stepInfo);
					}
		});
		
		return stepList;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> listPageInfo(String sql, final int firstResult, final int endResult) {
		final List<StepInfo> stepList = new LinkedList<StepInfo>();
		this.getJdbcTemplate().query(sql, 
		    new PreparedStatementSetter() {
			  @Override
		      public void setValues(PreparedStatement ps) throws SQLException {
				ps.setLong(1, firstResult);
				ps.setLong(2, endResult);
			  }
	        },	
		    new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				StepInfo stepInfo = new StepInfo();
				stepInfo.setId(rs.getInt("ID"));
				stepInfo.setStepNo(rs.getInt("STEP_NO"));
				stepInfo.setStepDesc(rs.getString("STEP_DESC"));
				stepInfo.setStepBeanName(rs.getString("STEP_BEAN_NAME"));
				stepInfo.setBatchNo(rs.getInt("BATCH_NO"));
				stepInfo.setJobNo(rs.getInt("JOB_NO"));
				stepInfo.setStepRunPeriod(rs.getString("STEP_RUN_PERIOD"));
				stepInfo.setChStepRunPeriod(BatchUtil.stepRunPeriodToChStr(rs.getString("STEP_RUN_PERIOD")));
				stepInfo.setStepCtrlFlgs(rs.getString("STEP_CTRL_FLGS"));
				stepInfo.setRecSt(rs.getString("REC_ST"));
				
				String ctrlFlgs = BatchUtil.stepCtrlFlgsToChStr(stepInfo);
				stepInfo.setChStepCtrlFlgs(ctrlFlgs);
				
				stepList.add(stepInfo);
			}
		});
		
		return (List<T>) stepList;
	}
}
